package com.andyou.modules.sys.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.andyou.common.config.Global;
import com.andyou.common.mapper.JsonMapper;
import com.andyou.common.persistence.Page;
import com.andyou.common.utils.DateUtils;
import com.andyou.common.utils.GridVO;
import com.andyou.common.utils.StringUtils;
import com.andyou.common.utils.excel.ExportExcel;
import com.andyou.common.web.BaseController;
import com.andyou.modules.sys.entity.SysUploadFile;
import com.andyou.modules.sys.service.SysUploadFileService;
import com.andyou.modules.sys.utils.MultipartFileUtil;
import com.google.common.collect.Lists;

/**
 * 上传文件(sys_upload_file)Controller
 * 
 * @author huanqxie@qq.com
 * @version 2018-10-31
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/sysUploadFile")
public class SysUploadFileController extends BaseController {

	@Autowired
	private SysUploadFileService sysUploadFileService;

	@ModelAttribute
	public SysUploadFile get(@RequestParam(required = false) String id) {
		SysUploadFile entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = sysUploadFileService.get(id);
		}
		if (entity == null) {
			entity = new SysUploadFile();
		}
		return entity;
	}

	//@RequiresPermissions("sys:sysUploadFile:view")
	@RequestMapping(value = { "sysUploadFileList", "" })
	public String list(SysUploadFile sysUploadFile, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		// Page<SysUploadFile> page = sysUploadFileService.findPage(new
		// Page<SysUploadFile>(request, response), sysUploadFile);
		// model.addAttribute("page", page);
		return "modules/sys/sysUploadFileList";
	}

	//@RequiresPermissions("sys:sysUploadFile:view")
	@ResponseBody
	@RequestMapping(value = { "sysUploadFileListJson" })
	public String sysUploadFileListJson(SysUploadFile sysUploadFile, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		Page<SysUploadFile> page = sysUploadFileService.findPage(new Page<SysUploadFile>(request,
				response, true), sysUploadFile);
		model.addAttribute("page", page);

		GridVO gridVO = new GridVO();
		gridVO.setRows(page.getList());
		gridVO.setTotal(page.getCount());

		return JsonMapper.getInstance().toJson(gridVO);
	}

	//@RequiresPermissions("sys:sysUploadFile:view")
	@RequestMapping(value = "sysUploadFileForm")
	public String form(SysUploadFile sysUploadFile, Model model) {
		model.addAttribute("sysUploadFile", sysUploadFile);
		return "modules/sys/sysUploadFileForm";
	}

	//@RequiresPermissions("sys:sysUploadFile:view")
	@RequestMapping(value = "sysUploadFileDetail")
	public String sysUploadFileDetail(SysUploadFile sysUploadFile, Model model) {
		model.addAttribute("sysUploadFile", sysUploadFile);
		return "modules/sys/sysUploadFileDetail";
	}

	//@RequiresPermissions(value = { "sys:sysUploadFile:edit", "sys:sysUploadFile:create" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(SysUploadFile sysUploadFile, Model model, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sysUploadFile)) {
			return form(sysUploadFile, model);
		}
		sysUploadFileService.save(sysUploadFile);
		renderStringByJbox(response, "提交成功");
		return null;

	}

	//@RequiresPermissions("sys:sysUploadFile:delete")
	@RequestMapping(value = "delete")
	public String delete(SysUploadFile sysUploadFile, RedirectAttributes redirectAttributes) {
		sysUploadFileService.delete(sysUploadFile);
		addMessage(redirectAttributes, "删除上传文件成功");
		return "redirect:" + Global.getAdminPath() + "/sys/sysUploadFile/?repage";
	}

	//@RequiresPermissions("sys:sysUploadFile:delete")
	@ResponseBody
	@RequestMapping(value = "deleteAjax")
	public String deleteAjax(SysUploadFile sysUploadFile, RedirectAttributes redirectAttributes) {
		sysUploadFileService.delete(sysUploadFile);
		return "删除成功";
	}

	//@RequiresPermissions("sys:sysUploadFile:delete")
	@ResponseBody
	@RequestMapping(value = "batchDelete")
	public String batchDelete(String ids, RedirectAttributes redirectAttributes) {

		String[] idsArr = ids.split(",");
		List<String> idList = Lists.newArrayList();
		idList = Arrays.asList(idsArr);
		sysUploadFileService.batchDelete(idList);
		return "删除成功";
	}
	
	/**
	 * 返回json
	 * @param ids
	 * @param redirectAttributes
	 * @return （参数是否可空/不可空）
	 * @author lgx
	 * Date:2018年12月3日；
	 */
	@ResponseBody
	@RequestMapping(value = "batchDeleteJson")
	public String batchDeleteJson(String ids, RedirectAttributes redirectAttributes) {

		String[] idsArr = ids.split(",");
		List<String> idList = Lists.newArrayList();
		idList = Arrays.asList(idsArr);
		sysUploadFileService.batchDelete(idList);
		
		return JsonMapper.toJsonString("删除成功");
	}

	@RequestMapping(value = "export")
	public String exportFile(SysUploadFile sysUploadFile, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "上传文件" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<SysUploadFile> page_ = new Page<SysUploadFile>(request, response, -1);
			page_.setPageSize(500000);
			sysUploadFile.setPage(page_);
			page_ = sysUploadFileService.findPage(page_, sysUploadFile);
			new ExportExcel("上传文件", SysUploadFile.class).setDataList(page_.getList())
					.write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出数据失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/sys/sysUploadFile/?repage";
	}

	/**
	 * 上传附件
	 * 
	 * @param std
	 * @param file
	 * @param model
	 * @param response
	 * @param redirectAttributes
	 * @param request
	 * @param returnform
	 * @param rootId
	 * @return （参数是否可空/不可空）
	 * @author lgx Date:2018年2月8日；
	 */
	@RequestMapping(value = "uploadfile")
	@ResponseBody
	public List<SysUploadFile> uploadfileByResume(Model model, HttpServletResponse response,
			RedirectAttributes redirectAttributes, MultipartHttpServletRequest request,
			String businessId, String businessName,String businessType) {

		List<MultipartFile> files = request.getFiles("file");
		MultipartFileUtil util = new MultipartFileUtil();
		List<SysUploadFile> sysUploadFiles = new ArrayList<SysUploadFile>();
		for (MultipartFile file : files) {
			util.setFile(file);
			SysUploadFile sysUploadFile = new SysUploadFile();

			String fileName = util.getOriginalFilename();

			String fileType = util.getFileType();

			String sysPath = Global.getConfig("uploadFilePath");

			Calendar c = Calendar.getInstance();
			String path1 = String.valueOf(c.get(Calendar.YEAR))
					+ String.valueOf(c.get(Calendar.MONTH) + 1)
					+ String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/";

			String path = sysPath + path1;
			String fileName1 = UUID.randomUUID().toString() + "." + fileType;

			File targetFile = new File(path, fileName1);

			sysUploadFile.setFileType(fileType);
			sysUploadFile.setFileSize(util.getSizeInString());
			sysUploadFile.setPath(path1 + fileName1);
			sysUploadFile.setFileName(fileName);
			sysUploadFile.setBusinessId(businessId);
			sysUploadFile.setBusinessName(businessName);
			sysUploadFile.setBusinessType(businessType);
			
			sysUploadFiles.add(sysUploadFile);

			if (util.isImage()) {
				BufferedImage image = util.getBufferedImage();
				sysUploadFile.setPicWidth(String.valueOf(image.getWidth()));
				sysUploadFile.setPicHeight(String.valueOf(image.getHeight()));
			}

			if (!targetFile.exists()) { // 判断文件的路径是否存在
				targetFile.mkdirs();
			}
			// 保存
			try {
				util.transferTo(targetFile); // 传送 失败就抛异常
				sysUploadFileService.save(sysUploadFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return sysUploadFiles;

	}

}